const express = require('express');
const router = express.Router();
const Student = require('../models/Student');

// 获取所有学生列表（支持分页、搜索、筛选）
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      keyword = '', 
      class: className = '',
      minScore,
      maxScore 
    } = req.query;

    // 构建查询条件
    const query = {};
    
    // 关键词搜索（姓名或学号）
    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { studentId: { $regex: keyword, $options: 'i' } }
      ];
    }
    
    // 班级筛选
    if (className) {
      query.class = className;
    }
    
    // 成绩范围筛选
    if (minScore !== undefined || maxScore !== undefined) {
      query.score = {};
      if (minScore !== undefined) query.score.$gte = Number(minScore);
      if (maxScore !== undefined) query.score.$lte = Number(maxScore);
    }

    // 分页参数
    const skip = (Number(page) - 1) * Number(limit);
    
    // 查询数据
    const students = await Student.find(query)
      .sort({ score: -1, createdAt: -1 })
      .skip(skip)
      .limit(Number(limit));
    
    // 获取总数
    const total = await Student.countDocuments(query);

    res.json({
      success: true,
      data: students,
      pagination: {
        total,
        page: Number(page),
        limit: Number(limit),
        pages: Math.ceil(total / Number(limit))
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '查询失败',
      error: error.message
    });
  }
});

// 获取单个学生详情
router.get('/:id', async (req, res) => {
  try {
    const student = await Student.findById(req.params.id);
    
    if (!student) {
      return res.status(404).json({
        success: false,
        message: '学生不存在'
      });
    }

    res.json({
      success: true,
      data: student
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '查询失败',
      error: error.message
    });
  }
});

// 创建学生
router.post('/', async (req, res) => {
  try {
    const { studentId, name, class: className, scores } = req.body;

    // 检查学号是否已存在
    const existingStudent = await Student.findOne({ studentId });
    if (existingStudent) {
      return res.status(400).json({
        success: false,
        message: '学号已存在'
      });
    }

    // 创建学生
    const student = new Student({
      studentId,
      name,
      class: className,
      scores: scores || []
    });

    await student.save();

    res.status(201).json({
      success: true,
      data: student,
      message: '学生创建成功'
    });
  } catch (error) {
    // 处理验证错误
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(err => err.message);
      return res.status(400).json({
        success: false,
        message: messages.join('; ')
      });
    }

    res.status(500).json({
      success: false,
      message: '创建失败',
      error: error.message
    });
  }
});

// 更新学生信息
router.put('/:id', async (req, res) => {
  try {
    const { name, class: className, scores } = req.body;

    const student = await Student.findByIdAndUpdate(
      req.params.id,
      { name, class: className, scores },
      { new: true, runValidators: true }
    );

    if (!student) {
      return res.status(404).json({
        success: false,
        message: '学生不存在'
      });
    }

    res.json({
      success: true,
      data: student,
      message: '更新成功'
    });
  } catch (error) {
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(err => err.message);
      return res.status(400).json({
        success: false,
        message: messages.join('; ')
      });
    }

    res.status(500).json({
      success: false,
      message: '更新失败',
      error: error.message
    });
  }
});

// 删除学生
router.delete('/:id', async (req, res) => {
  try {
    const student = await Student.findByIdAndDelete(req.params.id);

    if (!student) {
      return res.status(404).json({
        success: false,
        message: '学生不存在'
      });
    }

    res.json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除失败',
      error: error.message
    });
  }
});

// 获取所有班级列表
router.get('/filter/classes', async (req, res) => {
  try {
    const classes = await Student.distinct('class');
    
    res.json({
      success: true,
      data: classes.sort()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '查询失败',
      error: error.message
    });
  }
});

// 获取所有课程列表
router.get('/filter/courses', async (req, res) => {
  try {
    const students = await Student.find();
    const coursesSet = new Set();
    
    students.forEach(student => {
      if (student.scores && student.scores.length > 0) {
        student.scores.forEach(score => {
          coursesSet.add(score.courseName);
        });
      }
    });
    
    const courses = Array.from(coursesSet).sort();
    
    res.json({
      success: true,
      data: courses
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '查询失败',
      error: error.message
    });
  }
});

module.exports = router;
